package com.zhonglian.elisa.base;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.zhonglian.elisa.MainActivity;
import com.zhonglian.elisa.utils.LogUtil;
import com.zhonglian.elisa.utils.QRCodeCreate;
import com.zhonglian.elisa.utils.StatusBarUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import butterknife.ButterKnife;
import butterknife.Unbinder;


public abstract class BaseActivity extends AppCompatActivity {

    Unbinder bind;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("enter Activity", getClass().getSimpleName());
        //是否是PAD
        if (isPads(this)) {
            LogUtil.iYx("是Pad");
            QRCodeCreate.ELISA_GR = "*ELISA-GR2";
            //设置为横屏
            if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//横屏
            }
        } else {
            //设置为竖屏
            LogUtil.iYx("是手机");
            QRCodeCreate.ELISA_GR = "*ELISA-GR1";
            if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
            }
        }

        //沉浸式状态栏
        transparentStatusBar();
        //状态栏文字颜色,true为灰色，false为系统默认白(统一修改或在合适情况下调用修改)
        StatusBarUtil.setStatusTextColor(true, this);
        AppManager.getAppManager().addActivity(this);

        //初始化
        setContentView(initLayout());
        bind = ButterKnife.bind(this);
        initView();
        setViewPaddingTop();//沉浸后设置View与TOP的距离
    }

    public abstract int initLayout();

    public abstract void initView();

    /**
     * 沉浸式状态栏
     */
    public void transparentStatusBar() {
        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//大于等于5.0
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);// 透明状态栏
            if (checkDeviceHasNavigationBar()) {
                //有虚拟导航栏
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);//透明的状态栏和导航栏，必须API Level >= 21/5.0使用
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);// SDK21 清理状态栏半透明背景
                window.setStatusBarColor(Color.TRANSPARENT);// SDK21 将状态栏背景设置为透明
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//7.0 通过反射改变灰色状态栏背景为透明
            try {
                Class decorViewClazz = Class.forName("com.android.internal.policy.DecorView");
                Field field = decorViewClazz.getDeclaredField("mSemiTransparentStatusBarColor");
                field.setAccessible(true);
                field.setInt(getWindow().getDecorView(), Color.TRANSPARENT);  //改为透明
            } catch (Exception e) {
            }


        }
    }

    /**
     * 获取是否存在虚拟导航栏NavigationBar
     * true 有  false 无
     */
    public boolean checkDeviceHasNavigationBar() {
        boolean hasNavigationBar = false;
        Resources rs = getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
        }
        return hasNavigationBar;
    }


    /**
     * 设置布局距离上面的间距等于沉浸式状态栏高度
     */
    private void setViewPaddingTop() {
        //设置布局距离上面的间距等于沉浸式状态栏高度
        if (!(this instanceof MainActivity)) {//除MainActivity外（因为Main是在BaseFragment中设置与TOP距离）
            View nViews = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);//获取Activity布局最外层父布局
            if (nViews instanceof ViewGroup) {
                ViewGroup vp = (ViewGroup) nViews;
                View viewchild = vp.getChildAt(0);
                if (viewchild != null) {//很多时候沉浸式颜色 = 第一个子View颜色
                    LogUtil.iYx("--该Activity第一个子View的ID是:--" + viewchild.getId());
                    viewchild.setPadding(0, StatusBarUtil.statusBarHeight, 0, 0);
                } else {//否则直接设置父布局距TOP间距
                    nViews.setPadding(0, StatusBarUtil.statusBarHeight, 0, 0);
                }
            }
        }
    }

    /**
     * 到底是不是平板
     *
     * @param mContext
     * @return
     */
    public static boolean isPads(Context mContext) {
        if (isPad1(mContext)) {
            return true;//是
        }
        if (isPad2(mContext)) {
            return true;//是
        }
        return false;
    }

    /**
     * 判断当前设备是手机还是平板，代码来自 Google I/O App for Android
     *
     * @return 平板返回 True，手机返回 False
     */
    private static boolean isPad1(Context mContext) {
        return (mContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 判断当前屏幕尺寸是否大于6英寸
     *
     * @param mContext
     * @return
     */
    private static boolean isPad2(Context mContext) {
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;// 屏幕宽度（像素）
        float screenHeight = dm.heightPixels;// 屏幕高度
        double x = Math.pow(screenWidth / dm.xdpi, 2);
        double y = Math.pow(screenHeight / dm.ydpi, 2);
        // 屏幕尺寸
        double screenInches = Math.sqrt(x + y);
        // 大于6尺寸则为Pad
        if (screenInches >= 6.0) {
            LogUtil.iYx("--大于6英寸--");
            return true;
        }
        return false;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppManager.getAppManager().finishActivity(this);
        bind.unbind();
    }

}
